<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getUserCarsApi } from '@/api/car';
import { addMaintenanceAppointmentApi, addRepairAppointmentApi } from '@/api/appointment';
// 假设这是获取用户信息的API，实际应用中需要根据项目结构调整
import { queryInfoApi } from '@/api/user';

// 预约类型选项
const appointmentTypes = [
  { label: '车辆保养', value: 'maintenance' },
  { label: '车辆故障', value: 'repair' }
];

// 预约时间段选项
const timeSlots = [
  { label: '09:00-10:00', value: '09:00' },
  { label: '10:00-11:00', value: '10:00' },
  { label: '11:00-12:00', value: '11:00' },
  { label: '14:00-15:00', value: '14:00' },
  { label: '15:00-16:00', value: '15:00' },
  { label: '16:00-17:00', value: '16:00' }
];

// 预约表单数据
const appointmentForm = ref({
  userId: '', // 
  type: '', // 预约类型
  brand: '', // 品牌
  model: '', // 型号
  plateNumber: '', // 车牌号
  appointmentDate: '', // 预约日期
  appointmentTime: '', // 预约时间段
  description: '', // 描述/故障说明
  contactPhone: '' // 联系电话
});

// 检查状态
const submitLoading = ref(false)

// 直接使用所有时间段，不进行可用性检查
const availableTimeSlots = ref([...timeSlots]);

// 用户车辆列表（从API获取）
const carList = ref([]);

// 处理车辆选择变化
const handleCarChange = () => {
  const plateNumber = appointmentForm.value.plateNumber;
  // 找到选中的车辆
  const selectedCar = carList.value.find(car => car.plateNumber === plateNumber);
  if (selectedCar) {
    // 设置品牌和型号
    appointmentForm.value.brand = selectedCar.brand || '';
    appointmentForm.value.model = selectedCar.model || '';
  }
};

// 获取用户车辆列表
const fetchUserCars = async () => {
  try {
    const loginUserStr = localStorage.getItem('loginUser');
    
    const loginUser = JSON.parse(loginUserStr);
    const response = await getUserCarsApi(loginUser.id);
    // 重置车辆信息，防止使用旧值
    appointmentForm.value.brand = '';
    appointmentForm.value.model = '';
    appointmentForm.value.plateNumber = '';
    
    if (response && response.code) {
      carList.value = response.data || [];
      // 如果有车辆，默认选择第一辆，设置品牌、型号和车牌号
      if (carList.value.length > 0) {
        appointmentForm.value.brand = carList.value[0].brand || '';
        appointmentForm.value.model = carList.value[0].model || '';
        appointmentForm.value.plateNumber = carList.value[0].plateNumber || '';
      }
    } else {
      // 清空车辆列表
      carList.value = [];
      ElMessage.error('获取车辆列表失败：' + (response?.msg || '未知错误'));
    }
  } catch (error) {
    console.error('获取车辆列表异常:', error);
    // 确保发生异常时也清空车辆信息
    appointmentForm.value.brand = '';
    appointmentForm.value.model = '';
    appointmentForm.value.plateNumber = '';
    ElMessage.error('获取车辆列表时发生异常，请稍后重试');
  }
};

// 预约时间段选项
// 删除原有的timeSlots定义（现在已移到前面）

// 提交预约
const submitAppointment = async () => {
  // 表单验证
  if (!appointmentForm.value.type) {
    ElMessage.warning('请选择预约类型');
    return;
  }
  
  if (!appointmentForm.value.brand) {
    ElMessage.warning('请选择车辆品牌');
    return;
  }
  
  if (!appointmentForm.value.model) {
    ElMessage.warning('请选择车辆型号');
    return;
  }
  
  if (!appointmentForm.value.plateNumber) {
    ElMessage.warning('请选择车牌号');
    return;
  }
  
  if (!appointmentForm.value.appointmentDate) {
    ElMessage.warning('请选择预约日期');
    return;
  }
  
  if (!appointmentForm.value.appointmentTime) {
    ElMessage.warning('请选择预约时间');
    return;
  }
  
  if (!appointmentForm.value.contactPhone) {
    ElMessage.warning('请输入联系电话');
    return;
  }
  
  if (!appointmentForm.value.description) {
    ElMessage.warning('请输入描述/故障说明');
    return;
  }
  
  try {

    
    const loginUserStr = localStorage.getItem('loginUser');
    const loginUser = JSON.parse(loginUserStr);
    appointmentForm.value.userId = loginUser.id;
    
    const submitData = {
      ...appointmentForm.value,
      // 不包含carId字段，只传递brand、model和plateNumber
    };
    
    console.log('提交预约信息:', submitData);
    
    // 根据预约类型调用不同的API
    let result;
    if (appointmentForm.value.type === 'maintenance') {
      result = await addMaintenanceAppointmentApi(submitData);
    } else if (appointmentForm.value.type === 'repair') {
      result = await addRepairAppointmentApi(submitData);
    } else {
      ElMessage.error('无效的预约类型');
      return;
    }
    
    if (result.code) {
      ElMessage.success('预约提交成功！我们将尽快与您联系确认');
      
      // 重置表单
    appointmentForm.value.type = '';
    appointmentForm.value.brand = '';
    appointmentForm.value.model = '';
    appointmentForm.value.plateNumber = '';
    appointmentForm.value.appointmentDate = '';
    appointmentForm.value.appointmentTime = '';
    appointmentForm.value.description = '';
    appointmentForm.value.contactPhone = '';
    
    // 如果有车辆，重新选择第一辆，设置品牌、型号和车牌号
    if (carList.value.length > 0) {
      appointmentForm.value.brand = carList.value[0].brand;
      appointmentForm.value.model = carList.value[0].model;
      appointmentForm.value.plateNumber = carList.value[0].plateNumber;
    }
    } else {
      ElMessage.error('预约提交失败：' + (result.msg));
    }
  } catch (error) {

    ElMessage.error('预约失败，请重试');
    console.error('预约失败:', error);
  } finally {
    submitLoading.value = false;
  }
};

// 获取当前日期，用于日期选择器的最小日期
const getCurrentDate = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};


// 组件挂载时获取用户车辆列表和用户信息
onMounted(async () => {
  // 确保组件挂载时总是重置车辆信息
  appointmentForm.value.brand = '';
  appointmentForm.value.model = '';
  appointmentForm.value.plateNumber = '';
  
  const loginUserStr = localStorage.getItem('loginUser');
    
    const loginUser = JSON.parse(loginUserStr);
  
  // 获取用户信息
  const userInfoResponse = await queryInfoApi(loginUser.id);
  if (userInfoResponse && userInfoResponse.code && userInfoResponse.data && userInfoResponse.data.phone) {
    appointmentForm.value.contactPhone = userInfoResponse.data.phone;
  }
  
  // 获取车辆列表
  fetchUserCars();
});
</script>

<template>
  <div class="appointment-container">
    <h2>服务预约</h2>
    

    <!-- 预约卡片 -->
    <el-card class="appointment-card" :body-style="{ padding: '20px' }">
      <div class="appointment-info">
        <!-- 预约类型选择 -->
        <div class="section">
          <h3 class="section-title">预约类型</h3>
          <div class="type-selection">
            <el-radio-group v-model="appointmentForm.type" size="large">
              <el-radio-button 
                v-for="type in appointmentTypes" 
                :key="type.value" 
                :label="type.value"
                class="type-btn"
              >
                {{ type.label }}
              </el-radio-button>
            </el-radio-group>
          </div>
        </div>
        
        <!-- 预约表单 -->
        <el-form :model="appointmentForm" label-width="120px">
          <!-- 车辆选择 -->
          <el-form-item label="选择车辆" required>
            <el-select 
              v-model="appointmentForm.plateNumber" 
              placeholder="请选择您的车辆"
              style="width: 100%"
              @change="handleCarChange"
            >
              <el-option
                v-for="car in carList"
                :key="car.id"
                :label="`${car.plateNumber} - ${car.brand} ${car.model} (${car.year})`"
                :value="car.plateNumber"
                :data-brand="car.brand"
                :data-model="car.model"
              >
                <div class="option-content">
                  <div>
                    <div class="plate-number">{{ car.plateNumber }}</div>
                    <div class="car-info">{{ car.brand }} {{ car.model }} · {{ car.year }}</div>
                  </div>
                </div>
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 品牌和型号信息（根据选择的车辆自动填充） -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="品牌">
                <el-input v-model="appointmentForm.brand" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="型号">
                <el-input v-model="appointmentForm.model" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          
          <!-- 预约日期 -->
          <el-form-item label="预约日期" required>
            <el-date-picker
              v-model="appointmentForm.appointmentDate"
              type="date"
              placeholder="选择预约日期"
              :min-date="getCurrentDate()"
              :disabled-date="(time) => time.getTime() < Date.now() - 8.64e7"
              style="width: 100%"
            />
          </el-form-item>
          
          <!-- 预约时间 -->
          <el-form-item label="预约时间" required>
            <el-select
              v-model="appointmentForm.appointmentTime"
              placeholder="选择预约时间段"
              style="width: 100%"

            >
              <template v-if="availableTimeSlots.length > 0">
                <el-option
                  v-for="slot in availableTimeSlots"
                  :key="slot.value"
                  :label="slot.label"
                  :value="slot.value"
                />
              </template>
              <template v-else>
                <el-option
                  label="该日期暂无可用时间段"
                  value=""
                  disabled
                />
              </template>
            </el-select>

          </el-form-item>
          
          <!-- 联系电话 -->
          <el-form-item label="联系电话" required>
            <el-input
              v-model="appointmentForm.contactPhone"
              placeholder="请输入联系电话"
              style="width: 100%"
            />
          </el-form-item>
          
          <!-- 描述/故障说明 -->
          <el-form-item label="描述/故障说明" required>
            <el-input
              v-model="appointmentForm.description"
              type="textarea"
              :rows="4"
              placeholder="请输入车辆需求说明"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>
        
        <!-- 表单底部 -->
        <div class="form-actions">
          <el-button type="primary" @click="submitAppointment">
            确认提交
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.appointment-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.appointment-container h2 {
  margin-bottom: 20px;
  color: #303133;
}


.car-count {
  color: #606266;
  margin-left: 10px;
}

.appointment-card {
  margin-top: 20px;
  transition: all 0.3s ease;
}

.appointment-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.appointment-info {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.section {
  margin-bottom: 25px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #303133;
}

.type-selection {
  margin-bottom: 20px;
}

.type-btn {
  margin-right: 10px;
}

.option-content {
  display: flex;
  align-items: center;
}

.car-icon {
  font-size: 24px;
  margin-right: 10px;
}

.plate-number {
  font-weight: 600;
  color: #303133;
}

.car-info {
  color: #606266;
  font-size: 14px;
}

.form-actions {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

.time-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}
</style>